﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.Controllers.Result;
using Dm.Config;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Crypto;
using System.Security.Claims;

namespace DFGK_WMS.WebAPI.Controllers.物料管理
{
    /// <summary>
    /// 物料分类
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMaterialCategoryController : ControllerBase
    {
        public TMaterialCategoryController(ITMaterialCategoryRepository materialCategoryRepository)
        {
            MaterialCategoryRepository = materialCategoryRepository;
        }

        public ITMaterialCategoryRepository MaterialCategoryRepository { get; }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddMaterialCategory(TMaterialCategory m)
        {
            bool IsOK = MaterialCategoryRepository.AddTMaterialCategory(m);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败！编码已存在！", "500"));
        }
        #region 显示弃用
        ///// <summary>
        ///// 显示（暂时弃用）
        ///// </summary>
        ///// <param name="mname"></param>
        ///// <param name="pageIndex"></param>
        ///// <param name="pageSize"></param>
        ///// <returns></returns>
        //[HttpGet]
        //public IActionResult GetMaterialCategortList(string? mname = "", int pageIndex = 1, int pageSize = 3)
        //{
        //    if(pageIndex<=0 || pageSize<=0)
        //    {
        //        return Ok(BaseResult.Result("400", "分页条件有误！"));
        //    }
        //    int totalCount;
        //    var list = MaterialCategoryRepository.GetMaterialCategortList(mname, pageIndex, pageSize, out totalCount);
        //    if (list != null)
        //    {
        //        return Ok(BaseResult.Result(list, "查询成功", "200", totalCount));
        //    }
        //    return Ok(BaseResult.Result(null, "查询失败", "500", 0));
        //}
        #endregion

        /// <summary>
        /// 装备列表显示
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterialCategoryList(string? equipmentType, string? name, string? code, int pageIndex = 1, int pageSize = 3)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;
            var list = MaterialCategoryRepository.GetMaterialCategoryList(equipmentType, name, code, pageIndex, pageSize, out totalCount);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败", "500", 0));
        }

        /// <summary>
        /// 分类右侧显示
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="parent"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetParentMaterialCategortList(string? mname = "", int? parent = 0, int pageIndex = 1, int pageSize = 3)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;
            var list = MaterialCategoryRepository.GetParentMaterialCategortList(mname, parent, pageIndex, pageSize, out totalCount);
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败", "500", 0));
        }

        /// <summary>
        /// 添加-树形显示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterialCateMenuitemList()
        {
            var list = MaterialCategoryRepository.GetMaterialCateMenuitemList();
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "获取成功！", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！", "500"));
        }

        /// <summary>
        /// 根据Id获取对象信息
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTMaterialCategoryById(int mid)
        {
            if (mid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var rule = MaterialCategoryRepository.GetTMaterialCategoryById(mid);
            if (rule != null)
            {
                return Ok(BaseResult.Result(rule, "获取成功", "200"));
            }
            return Ok(BaseResult.Result(null, "获取失败！Id可能有误或已被删除！", "500"));
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdMaterialCategory(TMaterialCategory m)
        {
            if (m.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = MaterialCategoryRepository.UpdTMaterialCategory(m);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "修改成功", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败！编码已存在！", "500"));
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelMaterialCategory(int mid)
        {
            if (mid <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            bool IsOK = MaterialCategoryRepository.DelTMaterialCategory(mid);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "删除成功", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败！Id可能有误或已被删除！", "500"));
        }


        /// <summary>
        /// 导入Excel文件
        /// </summary>
        /// <param name="excelFile"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploaEquipmentCatalog(IFormFile file)
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Ok(BaseResult.Result("400", "没有选择文件或文件为空"));
                }
                string message = "";
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(BaseResult.Result("400", "必须是Excel文件"));
                }
                string uname = HttpContext.User.FindFirstValue("UserName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }

                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }

                ISheet sheet = wb.GetSheetAt(0);

                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;
                bool chongfu = false;
                bool dbchongfu = false;
                List<TMaterialCategory> categories = new();
                for (int i = 1; i <= totalRow; i++)
                {

                    IRow row = sheet.GetRow(i);

                    string? Name = row.GetCell(0)?.StringCellValue;
                    if(Name == "")
                    {
                        continue;
                    }
                    string? Code = row.GetCell(1)?.StringCellValue;
                    string? EquipmentType = row.GetCell(2)?.StringCellValue;
                    string? UnitName = row.GetCell(3)?.StringCellValue;
                    string? Manufacturer = row.GetCell(4)?.StringCellValue;
                    //string dateString = row.GetCell(3)?.StringCellValue; // 假设第四列是日期时间数据
                    //if (!string.IsNullOrEmpty(dateString) && DateTime.TryParse(dateString, out DateTime dateTime))
                    //{
                    //    DateTime? CreateDate = dateTime;
                    //    // 进行后续操作
                    //}


                    var materialCategory = new TMaterialCategory
                    {
                        Name = Name,
                        Code = Code,
                        EquipmentType = EquipmentType,
                        UnitName = UnitName,
                        Manufacturer = Manufacturer,
                        CreateDate = DateTime.Now,
                    };
                    categories.Add(materialCategory);
                }
                if (categories.Count <= 0)
                {
                    //message = "文件信息为空或别写字段为空！";
                    return Ok(BaseResult.Result(false, "导入失败！" + message, "500"));
                }

                var result = MaterialCategoryRepository.UpdateMaterialCategory(categories);
                wb.Close();

                if (result)
                {
                    return Ok(BaseResult.Result(true, "导入成功！" + message, "200"));
                }
                return Ok(BaseResult.Result(false, "导入失败！", "500"));
            }
            catch (Exception)
            {
                throw;
            }
        }


        /// <summary>
        /// 查询分类
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterialByType(string? categoryName )
        {
  
            var list = MaterialCategoryRepository.GetMaterialByType(categoryName);
            if (list.Count() >= 0)
            {
                return Ok(BaseResult.Result(list , "查询成功", "200"));
            }
            return Ok(BaseResult.Result(false, "查询失败", "500"));
        }
    }
}
